import json
import re
import random
from celery_tasks.sms.tasks import ccp_send_code
from django_redis import get_redis_connection
from aijiazufang.libs.captcha.captcha import captcha
from django.views import View
from django.http import HttpResponse,JsonResponse


class SMScodeView(View):
    """短信验证码接口"""

    def post(self, request):
        # 接受参数
        json_dict = json.loads(request.body)
        mobile = json_dict.get('mobile')
        id = json_dict.get('id')
        text = json_dict.get('text')

        # 检验参数
        if not all([mobile, id, text]):
            return JsonResponse({'errno': 4103,
                                 'errmsg': '缺少必要参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 4103,
                                 'errmsg': '手机号格式错误'})

        # 优化 防止频繁发送验证码
        # 链接redis
        redis_conn = get_redis_connection('verify_code')

        send = redis_conn.get(f'sen_{mobile}')
        if send:
            return JsonResponse({'errno': 4201,
                                 'errmsg': '验证频繁'})

        # 获取图形验证码
        ser_id = redis_conn.get(f'img_{id}')
        if not ser_id:
            return JsonResponse({'errno': 4002,
                                 'errmsg': '验证码不存在'})
        # 删除验证码
        try:
            redis_conn.delete(f'img_{id}')
        except Exception as e:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '删除失败'})
        # 对比图片验证码
        if text.lower() != ser_id.decode().lower():
            return JsonResponse({'errno': 4004,
                                 'errmsg': '图片验证码验证失败'})

        # 创建短信验证码
        sum = '%06d' % random.randint(0, 999999)
        print(sum)

        # 优化
        pl = redis_conn.pipeline()

        pl.setex(f'sms_{mobile}', 600, sum)
        pl.setex(f'sen_{mobile}', 60, 1)
        pl.execute()

        # 发送验证码
        # CCP().send_template_sms(mobile, [sum, 5], 1)
        ccp_send_code.delay(mobile, sum)

        return JsonResponse({'errno':0,
                             'errmsg':'发送成功'})



class ImageCodeView(View):

    def get(self, request):
        '''返回图形验证吗'''
        # 接收参数
        cur = request.GET.get('cur')

        # 校验参数是否齐全
        if not cur:
            return JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})

        # 调用captcha
        text, image = captcha.generate_captcha()

        # 链接redis
        redis_conn = get_redis_connection('verify_code')

        # 利用redis保存数据并设置有效期
        redis_conn.setex('img_%s' % cur, 300, text)

        # 返回
        return HttpResponse(image, content_type='image/jpg')




